<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="showDialogAction(null)" style="margin: 10px 0">新增
    </el-button>
    <el-table border="border" :data="tableData" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>

      <el-table-column align="center" prop="avatar" label="头像" width="180">
        <template slot-scope="{row,$index}">
          <el-image
            style="width: 50px; height: 50px"
            :src="filePrefix+row.avatar"
            :preview-src-list="[filePrefix+row.avatar]"
          >
          </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="nickName" label="昵称" width="100"></el-table-column>
      <el-table-column prop="userName" label="登录名称" width="100"></el-table-column>
      <el-table-column prop="cellPhone" label="电话" width="110"></el-table-column>
      <el-table-column prop="userStatus" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="enumFormat(scope.row.userStatus).color">{{ enumFormat(scope.row.userStatus).label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleNames" label="角色"></el-table-column>

      <el-table-column prop="lastLoginTime" label="最后登录时间" width="140"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="140"></el-table-column>
      <el-table-column prop="createBy" label="创建人" width="80"></el-table-column>


      <el-table-column prop="prop" label="操作" align="center" fixed="right" width="120">
        <template slot-scope="{row,$index}">
          <el-button @click="showDialogAction(row)" type="primary" icon="el-icon-edit" circle></el-button>
          <el-button @click="delAction(row)" type="danger" icon="el-icon-delete" circle></el-button>
        </template>
      </el-table-column>

    </el-table>
    <!--    current-page 当前页-->
    <el-pagination
      style="margin-top: 20px;text-align: center"
      @current-change="handleCurrentChange"
      :current-page.sync="pageDto.pageNum"
      :page-size="pageDto.pageSize"
      :page-count="7"
      background
      layout="total, prev, pager, next,jumper"
      :total="total"
    >
    </el-pagination>


    <el-dialog style="width: 80%" :title="title+'用户信息'" :before-close="handleClose"
               :visible.sync="dialogFormVisible"
    >
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item label="用户头像" prop="avatar" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="filePrefix+form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>

          </el-upload>
        </el-form-item>

        <el-form-item label="用户昵称" placeholder="请输入用户昵称" prop="nickName" :label-width="formLabelWidth">
          <el-input v-model="form.nickName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="用户姓名" placeholder="请输入用户姓名" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" placeholder="请输入用户电话" prop="cellPhone" :label-width="formLabelWidth">
          <el-input v-model="form.cellPhone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" placeholder="请输入用户密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <!--        1禁用 0启用-->
        <el-form-item label="是否显示" :label-width="formLabelWidth">
          <el-radio-group v-model="form.userStatus">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="checkedRoleIds" :label-width="formLabelWidth">
          <el-checkbox-group v-model="form.checkedRoleIds">
            <el-checkbox v-for="(item, index) in allRoles"
                         :key="item.roleId"
                         :label="item.roleId"
                         name="checkedRoleIds"
                         @change="handleCheckboxChange(item, $event)"
            >
              {{ item.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAction('ruleForm')">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addAction">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as api from './api'
import { Message } from 'element-ui'

export default {
  name: 'index',
  data() {
    return {
      title: '新增',
      pageDto: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      tableData: [],
      loading: false,
      dialogFormVisible: false,
      rules: {
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        cellPhone: [
          { required: true, message: '请输入用户电话', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请上传用户头像' }
        ],
        checkedRoleIds: [
          { type: 'array', required: true, message: '请选择用户角色', trigger: 'change' }
        ]
      },

      formLabelWidth: '100px',

      form: {
        userId: null,
        nickName: '',
        userName: '',
        password: '',
        cellPhone: '',
        avatar: '',
        userStatus: 0,
        roles: [],
        checkedRoleIds: []
      },
      allRoles: []
    }
  },
  // 组件加载完毕发出请求
  mounted() {
    this.pageAction()
    //加载用户角色
    this.roleListAction()
  },
  methods: {
    resetForm() {
      this.form = {
        userId: null,
        nickName: '',
        userName: '',
        password: '',
        cellPhone: '',
        avatar: '',
        userStatus: 0,
        roles: [],
        checkedRoleIds: []
      }
    },
    //点击切换页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageDto.pageNum = val
      this.pageAction()
    },
    //加载分页
    async pageAction() {
      let result = await api.pageRequest(this.pageDto)
      this.tableData = result.data.list
      this.total = result.data.total
    },
    cancelAction() {
      this.$refs.ruleForm.resetFields()
      this.dialogFormVisible = false
      this.resetForm()
    },
    //取消新增/编辑弹窗页面
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.resetFields()
          // this.$refs['ruleForm'].resetFields();
          // this.resetForm()
          done()
        })
        .catch(_ => {
        })
    },
    //打开弹窗
    showDialogAction(row) {
      if (row === null) {
        this.dialogFormVisible = true
        this.title = '新增'
        //浅拷贝、表格不会跟着变
        // this.form = {...row}
      } else {
        //浅拷贝、表格不会跟着变
        this.dialogFormVisible = true
        this.title = '编辑'
        api.detailRequest(row.userId).then(res => {
          this.form = res.data
        })
      }
    },
    addAction() {
      // <el-form :model="form"  ref="ruleForm"  :rules="rules">
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //请求接口
          this.loading = true
          api.addRequest(this.form).then(res => {
            if (200 === res.code) {
              this.loading = false
              //弹出提示
              this.$message({
                // message: res.msg,
                message: this.form.userId === null ? '新增成功' : '编辑成功',
                type: 'success'
              })
              //刷新页面
              this.pageAction()
              //清空form表单
              this.resetForm()
              //关闭弹窗
              this.dialogFormVisible = false
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    delAction(row) {
      this.$confirm('确认删除？')
        .then(_ => {
          api.delRequest(row.userId).then(res => {
            if (200 === res.code) {
              //弹出提示
              this.$message({
                message: res.msg,
                type: 'success'
              })
              //刷新页面
              this.pageAction()
            }
          })
        })
        .catch(_ => {
        })



    },
    handleAvatarSuccess(res, file) {
      if (res.code !== 200) {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
      this.form.avatar = res.data.url
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === 'image/jpeg';
      //   const isLt2M = file.size / 1024 / 1024 < 2;
      //
      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      //   }
      //   if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!');
      //   }
      //   return isJPG && isLt2M;
    },
    handleCheckboxChange(item, value) {
      // console.log(`Checkbox ${item.roleName} changed to ${value}`);
      // if (value) {
      //   this.form.checkedRoleIds.push(item.id)
      //   console.log(this.form.checkedRoleIds)
      // } else {
      //   this.form.checkedRoleIds = this.form.checkedRoleIds.filter(x => x != item.id)
      // }
      // console.log(this.form.checkedRoleIds)
    },
    //加载用户角色
    roleListAction() {
      api.roleListRequest().then(ress => {
        this.allRoles = ress.data
      })
    },

    enumFormat(val) {
      let itemTemp = {}
      this.$GlobalStatus.SYSTEM_STATUS.forEach(item => {
        if (item.type === val) {
          itemTemp = item
        }
      })
      return itemTemp
    }
  }
}


</script>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
